package cn.qdu.controller;

import cn.qdu.model.User;
import cn.qdu.service.UserService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.util.List;
import java.util.UUID;

@WebServlet("/UserRegisterServlet")
public class UserRegisterServlet extends HttpServlet {
    private UserService userService = new UserService();
    private static final int MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
    private static final int MAX_REQUEST_SIZE = 50 * 1024 * 1024; // 50MB

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 检查请求是否为文件上传类型
        if (!ServletFileUpload.isMultipartContent(request)) {
            request.setAttribute("error", "注册失败：请通过表单上传头像");
            request.getRequestDispatcher("/views/auth/register.jsp").forward(request, response);
            return;
        }

        try {
            System.out.println("进入 UserRegisterServlet 的 doPost 方法");

            // 配置上传参数
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(MAX_FILE_SIZE);
            upload.setSizeMax(MAX_REQUEST_SIZE);

            // 解析请求参数
            List<FileItem> formItems = upload.parseRequest(request);

            String userId = null, nickname = null, phone = null, email = null, password = null;
            String birthDateStr = null, gender = null;
            String avatarPath = null; // 头像保存路径

            // 处理表单字段
            for (FileItem item : formItems) {
                if (item.isFormField()) {
                    // 处理普通字段
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString("UTF-8");

                    switch (fieldName) {
                        case "userId":
                            userId = fieldValue;
                            break;
                        case "nickname":
                            nickname = fieldValue;
                            break;
                        case "phone":
                            phone = fieldValue;
                            break;
                        case "email":
                            email = fieldValue;
                            break;
                        case "password":
                            password = fieldValue;
                            break;
                        case "birthDate":
                            birthDateStr = fieldValue;
                            break;
                        case "gender":
                            gender = fieldValue;
                            break;
                    }
                } else {
                    // 在处理文件上传后，确保avatarPath被正确设置
                    if (item.getName() != null && !item.getName().isEmpty()) {
                        // 检查文件类型
                        String contentType = item.getContentType();
                        if (!contentType.startsWith("image/")) {
                            request.setAttribute("error", "注册失败：请上传图片格式的头像");
                            request.getRequestDispatcher("/views/auth/register.jsp").forward(request, response);
                            return;
                        }

                        // 生成唯一文件名
                        String fileName = UUID.randomUUID().toString() +
                                "." + FilenameUtils.getExtension(item.getName());

                        // 保存文件的目录（在项目部署目录下的 uploads 文件夹）
                        String uploadDir = getServletContext().getRealPath("/uploads/");
                        File uploadPath = new File(uploadDir);
                        if (!uploadPath.exists()) {
                            uploadPath.mkdirs();
                        }

                        // 保存文件
                        File storeFile = new File(uploadPath + File.separator + fileName);
                        item.write(storeFile);

                        // 保存相对路径到数据库（如：/uploads/xxx.jpg）
                        avatarPath = "/uploads/" + fileName;
                        System.out.println("头像上传成功，保存路径：" + avatarPath);
                    }
                }
            }

            // 验证必填字段
            if (password == null || password.trim().isEmpty()) {
                System.out.println("密码参数为空，未获取到值");
                request.setAttribute("error", "注册失败：密码不能为空");
                request.getRequestDispatcher("/views/auth/register.jsp").forward(request, response);
                return;
            }

            // 打印获取到的参数
            System.out.println("userId: " + userId);
            System.out.println("nickname: " + nickname);
            System.out.println("phone: " + phone);
            System.out.println("email: " + email);
            System.out.println("password: " + password);
            System.out.println("birthDateStr: " + birthDateStr);
            System.out.println("gender: " + gender);
            System.out.println("avatarPath: " + avatarPath);

            // 处理日期
            Date birthDate = null;
            if (birthDateStr != null && !birthDateStr.isEmpty()) {
                birthDate = Date.valueOf(birthDateStr);
            }

            // 创建用户对象（包含头像路径）
            User user = new User(userId, nickname, phone, email, avatarPath, birthDate, gender, password);

            // 注册用户
            if (userService.register(user)) {
                response.sendRedirect(request.getContextPath() + "/views/auth/login.jsp?registerSuccess=true");
            } else {
                request.setAttribute("error", "注册失败，用户ID、昵称、手机号或邮箱可能已被使用");
                request.getRequestDispatcher("/views/auth/register.jsp").forward(request, response);
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            request.setAttribute("error", "注册失败：文件上传错误 - " + e.getMessage());
            request.getRequestDispatcher("/views/auth/register.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "注册失败：" + e.getMessage());
            request.getRequestDispatcher("/views/auth/register.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/views/auth/register.jsp").forward(request, response);
    }
}